/**
 * Created by Administrator on 2017/7/5.
 */


let publicDao = require('./publicDao.js');
let tableName = 'recharge';

module.exports = rechargeDao;

function rechargeDao() {
    this.data = {};
    this.change = [];
}

rechargeDao.prototype.one = function (err, res, cb) {
    let _this = this;
    if (err !== null) {
        cb({code: err.code, msg: err.message}, null);
    } else if (res.length == 0) {
        cb(null, null);
    } else {
        _this.data = res[0];
        cb(null, {res: res[0]});
    }
};

rechargeDao.prototype.inId = function (id, cb) {
    //let publicModel = new publicDao();
    let _this = this;
    publicDao.init().table(tableName).wheres('id', '=', id).get(function (err, res) {
        _this.one(err, res, cb);
    });
};

rechargeDao.prototype.inGoodIdNotOk = function (uid,gid, cb) { 
    let _this = this;
    publicDao.init().table(tableName).wheres('userId','=',uid).wheres('goodsId','=',gid).wheres('status','=',0).get(function (err, res) {
        _this.one(err, res, cb);
    });
};

rechargeDao.prototype.set = function (key, value) {
    this.data[key] = value;
    this.change.push(key);

    return this;
};

rechargeDao.prototype.save = function (cb) {
    publicDao.init().table(tableName);
    if (!this.data.id) {
        for (let key in this.data) {
            publicDao.values(key, this.data[key]);
        }
        publicDao.insert(function (err, res) {
            if (err !== null) {
                cb({code: err.code, msg: err.message}, null);
            } else {
                cb(null, {res: res});
            }
        });
    } else {
        for (let i in this.change) {
            let key = this.change[i];
            publicDao.values(key, this.data[key]);
        }
        publicDao.wheres('id', '=', this.data.id);
        publicDao.update(function (err, res) {
            if (err !== null) {
                cb({code: err.code, msg: err.message}, null);
            } else {
                cb(null, {res: res});
            }
        });
    }
};